package dao;

import entity.Book;
import entity.jdba;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class BookDAO implements BookInterface{

    List<Book> list=jdba.getALLInfo();


    @Override
    public Book add(Book b) {
          if(selectById(b.getId())==null){
              if(selectById(b.getId())==null){
                  list.add(b);
                  jdba.Addbook(b);
                  return b;
              }

          }
        return null;
    }

    @Override
    public boolean delete(int b) {
        jdba.delete(b);
        return false;
    }

    @Override
    public boolean update(Book b) {
            for(Book book:list){
                if(book.getId()==b.getId()){
                    book.setAuthor(b.getAuthor());
                    book.setName(b.getName());
                    book.setPrice(b.getPrice());

                    System.out.println("11111111+"+b.getId());
                    jdba.update(b);
                    return true;
                }
            }
        return false;
    }

    @Override
    public Book selectById(int b) {
            for (Book book:list){
                if(book.getId()==b){
                    return book;
                }
            }
        return null;
    }

    @Override
    public Book selectByName(Book b) {
        for (Book book:list){
            if(book.getName().toUpperCase()==b.getName().toUpperCase()){
                return book;
            }
        }
        return null;
    }

    @Override
    public List<Book> selectAll() {
        return list;
    }

    public boolean exist(int id) {
        System.out.println("调用login");


        ResultSet resultSet= jdba.execute2("SELECT COUNT(*) FROM book WHERE id= ? ", String.valueOf(id));
        //  String sql = "select * from userdao where username = ? and password = ?";


        try {
            resultSet.next();
            int anInt = resultSet.getInt(1);
            if (anInt == 0) return false;
            else return true;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return false;
    }
}
